const btn = document.querySelector(`.fixed-container #send-message`)
btn.addEventListener('click',sendMessage)


function sendMessage() {
    let inputBox = document.querySelector("#user-input");
    let userMessage = inputBox.value.trim();

    if (userMessage !== "") {
        // 获取聊天容器
        let chatContainer = document.querySelector("#chat-container");

        // 创建用户消息气泡
        let userBubble = document.createElement("div");
        userBubble.classList.add("message", "user-message");
        userBubble.textContent = userMessage;
        chatContainer.appendChild(userBubble);

        // 发送请求到 Django 后端
        fetch("/chat/api/", {
            method: "POST",
            headers: { "Content-Type": "application/json; charset=UTF-8" },
            body: JSON.stringify({ message: userMessage }) // 发送用户输入
        })
        .then(response => response.json()) // 解析 JSON
        .then(data => {
            if (data.reply) {
                // 设置AI容器
                let aiMessageContainer = document.createElement("div");
                aiMessageContainer.style.display = "flex";
                aiMessageContainer.style.alignItems = "flex-start";

                // 创建AI头像
                let aiAvatar = document.createElement("img");
                aiAvatar.src = "/static/images/ai_avatar.png";
                aiAvatar.classList.add("ai-avatar");

                // 创建AI回复气泡
                let aiBubble = document.createElement("div");
                aiBubble.classList.add("message", "ai-message");
                aiBubble.textContent = data.reply;

                // 结合头像与回复（关键修改点）
                aiMessageContainer.appendChild(aiAvatar);
                aiMessageContainer.appendChild(aiBubble);

                // 添加内容至聊天页面（关键修改点）
                chatContainer.appendChild(aiMessageContainer);
            }
        })
        .catch(error => console.error("请求失败:", error));

        // 清空输入框
        inputBox.value = "";
    }
}

// 监听使用Enter键的"发送"按钮事件
document.querySelector("#user-input").addEventListener("keypress", function(event) {
    if (event.key === "Enter") {
        sendMessage();
    }
});